package com.zut.wx.handler;

import com.zut.wx.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class TextMsgHandler implements WxChatMsgHandle{

    @Resource
    private RedisUtil redisUtil;

    private static final String loginKey="loginCode";

    @Override
    public WxChatMsgTypeEnums getEnumByType() {

        return WxChatMsgTypeEnums.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String, String> mapMsg) {
        String content="验证码";
        //对接受到的公众号消息进行逻辑处理
        String fromUserName = mapMsg.get("FromUserName");
        String toUserName = mapMsg.get("ToUserName");
        String data="您的验证码为：";
        Random random = new Random();
        int i = random.nextInt(1000);
        String content1 = mapMsg.get("Content");

        if (content1.equals(content)){
            String text="<xml>\n" +
                    "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                    "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                    "  <CreateTime>12345678</CreateTime>\n" +
                    "  <MsgType><![CDATA[text]]></MsgType>\n" +
                    "  <Content><![CDATA["+data+i+",5分钟内有效"+"]]></Content>\n" +
                    "</xml>";

            //将生成的验证码加入缓存
            String nameKey = redisUtil.buildKey(loginKey,String.valueOf(i));
            redisUtil.setNx(nameKey,fromUserName,5L, TimeUnit.MINUTES);
            return text;
        }


       return null;

    }
}
